﻿using Aliyun.OSS;
using Core.FrameWork.Commons.Hepler.Validate;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Storage.AliyunOSS
{
    /// <summary>
    /// 阿里云OSS帮助类
    /// 未经测试
    /// </summary>
    public static class OSSHelper
    {
        /// <summary>
        /// 上传文件至OSS(单文件)
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="fileName"></param>
        /// <param name="fileType"></param>
        /// <param name="expirTime"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> SaveFile(this byte[] bytes, string fileName, BlobFileType fileType = BlobFileType.Image, DateTime expirTime = default)
        {
            var _client = new OssClient(Configs.OSS.Endpoint, Configs.OSS.AccessKeyId, Configs.OSS.AccessKeySecret);

            ObjectMetadata objectMeta = new ObjectMetadata
            {
                //设置内容长度
                ContentLength = bytes.Length,
            };

            string mime = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
            if (mime.ToLower() == ".svg")
            {
                objectMeta.ContentType = "image/svg+xml";
            }
            if (mime.ToLower() == ".pdf")
            {
                objectMeta.ContentType = "application/pdf";
            }
            if (mime.ToLower() == ".mp4")
            {
                objectMeta.ContentType = "video/mp4";
            }



            //设置过期时间
            if (expirTime != default)
            {
                objectMeta.ExpirationTime = expirTime;
            }

            Stream stream = new MemoryStream(bytes);

            var result = _client.PutBigObject(Configs.OSS.BucketName, fileName, stream, objectMeta);
            if (result.HttpStatusCode.ToString() != "OK")
            {
                throw new Exception($"阿里云上传失败");
            }
            await Task.CompletedTask;

            return Configs.OSS.wwwroot + fileName;
        }

        /// <summary>
        /// 上传图片至OSS(单文件)
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="strBase64"></param>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public static async Task<string> OSSPutImg(string FileName, string strBase64)
        {

            var _client = new OssClient(Configs.OSS.Endpoint, Configs.OSS.AccessKeyId, Configs.OSS.AccessKeySecret);
            //自动获取文件名
            string ImgExtend = string.Empty;
            //获取图片文件流
            Stream stream = ValidateHelper.Base64ToStream(strBase64, out var flag, out ImgExtend);

            ObjectMetadata objectMeta = new ObjectMetadata
            {
                //设置内容长度
                ContentLength = stream.Length,
                //设置内容类型
                ContentType = "image/jpeg"
            };
            var putObjectRequest = new PutObjectRequest(Configs.OSS.BucketName, FileName + "." + ImgExtend, stream, objectMeta);

            var result = _client.PutObject(putObjectRequest);
            if (result.HttpStatusCode.ToString() != "OK")
            {
                flag = false;
            }
            stream.Close();
            stream.Dispose();

            return Configs.OSS.wwwroot + FileName + "." + ImgExtend;


        }

        /// <summary>
        /// 上传图片至OSS(多文件)
        /// </summary>
        /// <param name="DicBase64"></param>
        /// <param name="DicImgStatus"></param>
        /// <param name="strURL"></param>
        /// <returns></returns>
        public static bool OSSPutMultipleImg(Dictionary<string, string> DicBase64, ref Dictionary<int, int> DicImgStatus, ref string[] strURL)
        {
            bool flag = true;
            try
            {
                var _client = new OssClient(Configs.OSS.Endpoint, Configs.OSS.AccessKeyId, Configs.OSS.AccessKeySecret);
                for (int i = 0; i < DicBase64.Count; i++)
                {
                    if (DicImgStatus.ElementAt(i).Value == 1)
                    {
                        //自动获取文件名
                        string ImgExtend = string.Empty;
                        //获取图片文件流
                        Stream stream = ValidateHelper.Base64ToStream(DicBase64.ElementAt(i).Value, out flag, out ImgExtend);
                        if (flag)
                        {
                            ObjectMetadata objectMeta = new ObjectMetadata
                            {
                                //设置内容长度
                                ContentLength = stream.Length,
                                //设置内容类型
                                ContentType = "image/jpeg"
                            };
                            var result = _client.PutObject(Configs.OSS.BucketName, DicBase64.ElementAt(i).Key + "." + ImgExtend, stream, objectMeta);
                            if (result.HttpStatusCode.ToString() != "OK")
                            {
                                DicImgStatus[i] = -1;
                            }
                            else
                            {
                                strURL[i] = Configs.OSS.wwwroot + DicBase64.ElementAt(i).Key + "." + ImgExtend;
                            }
                            stream.Close();
                            stream.Dispose();
                        }
                        else
                        {
                            DicImgStatus[i] = -1;
                        }
                    }
                }
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 删除OSS文件
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public static bool OSSFilesDel(string FileUrl)
        {
            bool flag;
            try
            {
                var _client = new OssClient(Configs.OSS.Endpoint, Configs.OSS.AccessKeyId, Configs.OSS.AccessKeySecret);
                _client.DeleteObject(Configs.OSS.BucketName, FileUrl.Replace(Configs.OSS.wwwroot, ""));
                flag = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }

        /// <summary>
        /// 删除OSS文件
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public static bool OSSFilesExists(string FileUrl)
        {
            bool flag;
            try
            {
                var _client = new OssClient(Configs.OSS.Endpoint, Configs.OSS.AccessKeyId, Configs.OSS.AccessKeySecret);
                flag = _client.DoesObjectExist(Configs.OSS.BucketName, FileUrl.Replace(Configs.OSS.wwwroot, ""));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return flag;
        }
    }
}
